import React, { PureComponent } from 'react';
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';
import { Spin, Tag, Menu, Icon, Avatar, Tooltip, message } from 'antd';
import moment from 'moment';
import groupBy from 'lodash/groupBy';
import router from 'umi/router';
import NoticeIcon from '../NoticeIcon';
import HeaderSearch from '../HeaderSearch';
import HeaderDropdown from '../HeaderDropdown';
import SelectLang from '../SelectLang';
import styles from './index.less';

export default class GlobalHeaderRight extends PureComponent {
  getNoticeData() {
    const { notices = [] } = this.props;
    if (notices.length === 0) {
      return {};
    }
    const newNotices = notices.map(notice => {
      const newNotice = { ...notice };
      if (newNotice.datetime) {
        newNotice.datetime = moment(notice.datetime).fromNow();
      }
      if (newNotice.id) {
        newNotice.key = newNotice.id;
      }
      if (newNotice.extra && newNotice.status) {
        const color = {
          todo: '',
          processing: 'blue',
          urgent: 'red',
          doing: 'gold',
        }[newNotice.status];
        newNotice.extra = (
          <Tag color={color} style={{ marginRight: 0 }}>
            {newNotice.extra}
          </Tag>
        );
      }
      return newNotice;
    });
    return groupBy(newNotices, 'type');
  }

  getUnreadData = noticeData => {
    const unreadMsg = {};
    Object.entries(noticeData).forEach(([key, value]) => {
      if (!unreadMsg[key]) {
        unreadMsg[key] = 0;
      }
      if (Array.isArray(value)) {
        unreadMsg[key] = value.filter(item => !item.read).length;
      }
    });
    return unreadMsg;
  };

  changeReadState = clickedItem => {
    const { id } = clickedItem;
    const { dispatch } = this.props;
    dispatch({
      type: 'global/changeNoticeReadState',
      payload: id,
    });
  };

  refresh() {
    window.location.reload(true);
  }

  render() {
    const {
      currentUser,
      fetchingNotices,
      onNoticeVisibleChange,
      onMenuClick,
      onCollectionMenuClick,
      onNoticeClear,
      theme,
      collection
    } = this.props;
    // debugger
    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
        {/* <Menu.Item key="userCenter"> */}
        {/*  <Icon type="user" /> */}
        {/*  <FormattedMessage id="menu.account.center" defaultMessage="account center" /> */}
        {/* </Menu.Item> */}
        {/* <Menu.Item key="userinfo"> */}
        {/*  <Icon type="setting" /> */}
        {/*  <FormattedMessage id="menu.account.settings" defaultMessage="account settings" /> */}
        {/* </Menu.Item> */}
        {/* <Menu.Item key="triggerError"> */}
        {/*  <Icon type="close-circle" /> */}
        {/*  <FormattedMessage id="menu.account.trigger" defaultMessage="Trigger Error" /> */}
        {/* </Menu.Item> */}
        {/* <Menu.Divider /> */}
        <Menu.Item key="logout">
          <Icon type="logout" />
          <FormattedMessage id="menu.account.logout" defaultMessage="logout" />
        </Menu.Item>
      </Menu>
    );
    let cmenu = [];
    for (let i = 0; i < collection.length; i++) {
      const item = collection[i];
      cmenu.push(<Menu.Item key={item.url}>
        <FormattedMessage  id = {item.permissionname} defaultMessage={item.permissionname} />
      </Menu.Item>)
    }
    let collectionMenu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={onCollectionMenuClick}>
        {cmenu}
      </Menu>
    );
    const noticeData = this.getNoticeData();
    const unreadMsg = this.getUnreadData(noticeData);
    const v = localStorage.getItem('antd-pro-authority');
    if (v === null) {
      router.push('/user/login');
      return false;
    }
    const sTemp = v.substring(1, v.length - 1);
    const sArray = sTemp.split(',');
    const Name = sArray[0].substring(1, sArray[0].length - 1).toString();
    window.userName = Name;
    const className = styles.right;
    return (
      <div className={styles.right}>
        <Icon
          type="sync"
          key="Icon"
          style={{ marginRight: '1rem' }}
          onClick={this.refresh.bind(this)}
        />
        <HeaderDropdown overlay={collectionMenu}    style={{ marginRight: '1rem' }}>
            <span className={`${styles.action} ${styles.account}`}>
              <Icon type="star"  style={{ marginRight: '0.5rem' ,fontSize:'1rem', lineHeight:"normal"}}/>
                <span className={styles.name}>收藏菜单</span>
            </span>
        </HeaderDropdown>



        {/*   <HeaderSearch
          className={`${styles.action} ${styles.search}`}
          placeholder={formatMessage({ id: 'component.globalHeader.search' })}
          dataSource={[
            formatMessage({ id: 'component.globalHeader.search.example1' }),
            formatMessage({ id: 'component.globalHeader.search.example2' }),
            formatMessage({ id: 'component.globalHeader.search.example3' }),
          ]}
          onSearch={value => {
            console.log('input', value); // eslint-disable-line
          }}
          onPressEnter={value => {
            console.log('enter', value); // eslint-disable-line
          }}
        /> */}
        {/* <Tooltip title={formatMessage({ id: 'component.globalHeader.help' })}> */}
        {/*  <a */}
        {/*    target="_blank" */}
        {/*    href="https://pro.ant.design/docs/getting-started" */}
        {/*    rel="noopener noreferrer" */}
        {/*    className={styles.action} */}
        {/*  > */}
        {/*    <Icon type="question-circle-o" /> */}
        {/*  </a> */}
        {/* </Tooltip> */}
        {/* <NoticeIcon */}
        {/*  className={styles.action} */}
        {/*  count={currentUser.unreadCount} */}
        {/*  onItemClick={(item, tabProps) => { */}
        {/*    console.log(item, tabProps); // eslint-disable-line */}
        {/*    this.changeReadState(item, tabProps); */}
        {/*  }} */}
        {/*  loading={fetchingNotices} */}
        {/*  locale={{ */}
        {/*    emptyText: formatMessage({ id: 'component.noticeIcon.empty' }), */}
        {/*    clear: formatMessage({ id: 'component.noticeIcon.clear' }), */}
        {/*    viewMore: formatMessage({ id: 'component.noticeIcon.view-more' }), */}
        {/*    notification: formatMessage({ id: 'component.globalHeader.notification' }), */}
        {/*    message: formatMessage({ id: 'component.globalHeader.message' }), */}
        {/*    event: formatMessage({ id: 'component.globalHeader.event' }), */}
        {/*  }} */}
        {/*  onClear={onNoticeClear} */}
        {/*  onPopupVisibleChange={onNoticeVisibleChange} */}
        {/*  onViewMore={() => message.info('Click on view more')} */}
        {/*  clearClose */}
        {/* > */}
        {/*  <NoticeIcon.Tab */}
        {/*    count={unreadMsg.notification} */}
        {/*    list={noticeData.notification} */}
        {/*    title="notification" */}
        {/*    emptyText={formatMessage({ id: 'component.globalHeader.notification.empty' })} */}
        {/*    emptyImage="https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg" */}
        {/*    showViewMore */}
        {/*  /> */}
        {/*  <NoticeIcon.Tab */}
        {/*    count={unreadMsg.message} */}
        {/*    list={noticeData.message} */}
        {/*    title="message" */}
        {/*    emptyText={formatMessage({ id: 'component.globalHeader.message.empty' })} */}
        {/*    emptyImage="https://gw.alipayobjects.com/zos/rmsportal/sAuJeJzSKbUmHfBQRzmZ.svg" */}
        {/*    showViewMore */}
        {/*  /> */}
        {/*  <NoticeIcon.Tab */}
        {/*    count={unreadMsg.event} */}
        {/*    list={noticeData.event} */}
        {/*    title="event" */}
        {/*    emptyText={formatMessage({ id: 'component.globalHeader.event.empty' })} */}
        {/*    emptyImage="https://gw.alipayobjects.com/zos/rmsportal/HsIsxMZiWKrNUavQUXqx.svg" */}
        {/*    showViewMore */}
        {/*  /> */}
        {/* </NoticeIcon> */}
        {
          /*          currentUser.name ? (
                    <HeaderDropdown overlay={menu}>
                      <span className={`${styles.action} ${styles.account}`}>
                        <Avatar
                          size="small"
                          className={styles.avatar}
                          src={currentUser.avatar}
                          alt="avatar"
                        />
                        <span className={styles.name}>{currentUser.name}</span>
                      </span>
                    </HeaderDropdown>
                  ) : (
                    <Spin size="small" style={{ marginLeft: 8, marginRight: 8 }} />
                  ) */
          <HeaderDropdown overlay={menu}>
            <span className={`${styles.action} ${styles.account}`}>
              <Avatar
                size="small"
                className={styles.avatar}
                src="https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png"
                alt="avatar"
              />
              <span className={styles.name}>{Name}</span>
            </span>
          </HeaderDropdown>
        }
        <SelectLang className={styles.action} />
      </div>
    );
  }
}
